package com.gx.smart.building.ui.inspection.fragment

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.TimeUtils
import com.gx.smart.base.BaseMVVMFragmentV2
import com.gx.smart.building.R
import com.gx.smart.building.databinding.FragmentInspectionTaskCompleteDetailBinding
import com.gx.smart.building.ui.common.adapter.ImageAdapter
import com.gx.smart.building.ui.inspection.adapter.InspectionResultAdapter
import com.gx.smart.building.ui.inspection.viewmodel.InspectionViewModel
import com.gx.smart.building.ui.photo.activity.CustomActivity
import com.gx.smart.building.ui.photo.fragment.PhotoPreviewFragment
import com.gx.smart.building.ui.photo.model.ImageViewInfo
import com.gx.smart.lib_http.BuildConfig
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskAssetDto
import com.previewlibrary.GPreviewBuilder

class InspectionTaskCompleteDetailFragment : BaseMVVMFragmentV2<InspectionViewModel>() {
    private lateinit var viewBinding: FragmentInspectionTaskCompleteDetailBinding
    private lateinit var resultAdapter: InspectionResultAdapter
//    private lateinit var planTaskAssetDto: PlanTaskAssetDto.Builder

    override fun onBindLayout(): Int = R.layout.fragment_inspection_task_complete_detail

    override fun getToolbarTitle(): String = "任务详情"

    override fun onBindViewModel(): Class<InspectionViewModel> = InspectionViewModel::class.java

    override fun initContentView(root: ViewGroup) {
        viewBinding =
            FragmentInspectionTaskCompleteDetailBinding.inflate(layoutInflater, root, true)
    }

    override fun initContent() {
        super.initContent()
        viewBinding.resultStatus.setOnCheckedChangeListener { _, isChecked ->
            //巡检/保养状态：1-正常，2-异常
//            planTaskAssetDto.resultStatus = if (isChecked) 2 else 1
        }
        viewBinding.resultDesc.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable) {
                viewBinding.wordCount.text = s.length.toString() + "/200"
            }
        })

    }

    override fun initData() {
        viewModel.queryPlanTaskAssetDetail(
            requireActivity().intent.getStringExtra("planTaskId")!!,
            requireActivity().intent.getStringExtra("assetId")!!
        )
        viewModel.detail.observe(viewLifecycleOwner) {
//            planTaskAssetDto = PlanTaskAssetDto.newBuilder(it)

            viewBinding.assetCode.text = it.assetCode
            viewBinding.assetName.text = it.assetName
            viewBinding.assetTypeName.text = it.assetTypeName
            viewBinding.brandName.text = it.brandName
            viewBinding.modelName.text = it.modelName
            viewBinding.areaName.text = it.areaName
            handleStatus(it.handleStatus)
            //巡检/保养状态：1-正常，2-异常
            viewBinding.resultStatus.isChecked = it.resultStatus == 2
            viewBinding.resultDesc.apply {
                text = Editable.Factory.getInstance().newEditable(it.resultDesc)
            }
            viewBinding.finishTime.text =
                TimeUtils.millis2String(it.handleTime, "yyyy-MM-dd HH:mm:ss")

        }
        viewModel.detailResultList.observe(viewLifecycleOwner) { it ->
            resultAdapter.refresh(it)
        }
    }

    //状态：1-已处理，2-未处理
    private fun handleStatus(handleStatus: Int) {
        viewBinding.resultStatus.isEnabled = false
        viewBinding.resultDesc.isEnabled = false
        imageAdapter()
        resultAdapter =
            InspectionResultAdapter(
                requireActivity(), 1, null, null,
                viewModel, null
            )
        viewBinding.resultRecyclerView.adapter = resultAdapter
        viewModel.detailResultList.observe(viewLifecycleOwner) { it ->
            resultAdapter.refresh(it)
        }
    }

    private fun imageAdapter() {
        viewBinding.imageRecyclerView.visibility = View.VISIBLE
        val imageAdapter = ImageAdapter(requireContext())
        viewBinding.imageRecyclerView.adapter = imageAdapter
        val imageViewInfoList: MutableList<ImageViewInfo> = mutableListOf()
        imageAdapter.setItemClickListener { _, position ->
            run {
                val bundle = Bundle()
                bundle.putSerializable("className", PhotoPreviewFragment::class.java)
                GPreviewBuilder.from(requireActivity())
                    .to(CustomActivity::class.java, bundle)
                    .setData(imageViewInfoList)
                    .setIsScale(true)
                    .setCurrentIndex(position)
                    .setSingleFling(true) //是否在黑屏区域点击返回
                    .setDrag(true) //是否禁用图片拖拽返回
                    .setType(GPreviewBuilder.IndicatorType.Number) //指示器类型
                    .start()
            }
        }
        viewModel.detailFileList.observe(viewLifecycleOwner) { it ->
            imageViewInfoList.clear()
            it.map { workOrderFile ->
                val imageViewInfo =
                    ImageViewInfo(BuildConfig.FILE_UPLOAD_URL + workOrderFile.fileUrl)
                imageViewInfoList.add(imageViewInfo)
            }
            imageAdapter.addAll(it.map {
                BuildConfig.FILE_UPLOAD_URL + it.fileUrl
            })
        }
    }

}